package org.algorithm.wE1.链表;

import org.algorithm.biubiu.wheel_1.common.ListNode;

/**
 * @Date 2022/2/18
 * @Link {https://leetcode-cn.com/problems/aMhZSa/}
 */
public class 回文链表 {
        public static void main(String[] args) {
        int[] arr = {1,2,3,2,1};
        ListNode node =ListNode.build(arr);
            System.out.println(isPalindrome(node));
    }

    public static boolean isPalindrome(ListNode head){
        //找到中间节点
        ListNode s = head;
        ListNode f = head;
        while(f.next != null && f.next.next != null){
            s = s.next;
            f = f.next.next;
        }
        ListNode node = s.next;
        //截断
        s.next = null;
        //翻转后半部分
        System.out.println(ListNode.print(node));
        ListNode pre = reverseListNode(node);
        System.out.println(ListNode.print(pre));
        while (head != null&&pre !=null){
            if(head.val != pre.val){
                return false;
            }
            head = head.next;
            pre = pre.next;
        }
        return true;
    }

    private static ListNode reverseListNode(ListNode node){
        if(node == null || node.next == null){
            return node;
        }
        ListNode pre = null;
        ListNode curr = node;
        while(curr != null){
            ListNode next = curr.next;
            curr.next = pre;
            pre = curr;
            curr = next;
        }
      return pre;
    }
}
